package com.yhp.service.impl;

import com.yhp.bean.Menu;
import com.yhp.bean.Role;
import com.yhp.dao.MiddleDao;
import com.yhp.dao.RoleDao;
import com.yhp.dao.impl.MiddleDaoImpl;
import com.yhp.dao.impl.RoleDaoImpl;
import com.yhp.service.RoleService;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class RoleServiceImpl implements RoleService {
    private RoleDao roleDao=new RoleDaoImpl();
    private MiddleDao middleDao=new MiddleDaoImpl();
    @Override
    public List<Role> getRoleList(int pageIndex, int pageSize) {
        return roleDao.getRoleList(pageIndex, pageSize);
    }

    @Override
    public int total() {
        return roleDao.total();
    }

    @Override   //事务问题
    public int insertRole(String rolename, String state, String[] ids) {
        int k1=0;
        try {
            //1.新增角色表
            Role role = new Role();
            role.setRoleName(rolename);
            role.setRoleState(Integer.parseInt(state));
            int k = roleDao.insert(role);
            //2.新增中间表
            //如何获得新增数据的id?
            middleDao.insertMiddle(k,ids);
            k1=1;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        return k1;
    }

    @Override
    public int update(int roleState,int roleId) {
        return roleDao.update(roleState,roleId);
    }

    @Override
    public Role findbyid(int roleid) {
        return roleDao.findbyid(roleid);
    }

    @Override
    public List<Menu> better(List<Menu> mz, List<Menu> mr) {
        //进行对比把mz中的mr进行标记,设1为共有的0为无，返回一个附加属性的MenuList
        List<Menu> rms = new ArrayList<>();
        for (Menu z1 : mz) {
            for (Menu r1 : mr) {
                if(Objects.equals(z1.getMenuId(), r1.getMenuId())){
                     z1.setRoleState(1);//对一级菜单进行对比添加属性
                    System.out.println("一级菜单"+z1.getMenuName()+"是共存的");
                }else {
                for (int a=0 ;a<z1.getSecondMenuList().size();a++){//对两种for灵活运用
                        if (Objects.equals(z1.getSecondMenuList().get(a).getMenuId(), r1.getMenuId()) ){
                            z1.getSecondMenuList().get(a).setRoleState(1);//对二级菜单进行对比添加属性
                            System.out.println("二级菜单"+z1.getSecondMenuList().get(a).getMenuName()+"是共存的");
                        }
                }
                }
            }
            //每次对改变后的z2存入对应的z1，
            rms.add(z1);//受for刷新z1会消失，用rms存入对比过后的z1
        }
        return rms;
    }

    @Override
    public boolean update(String[] menuId, Role role) {
        //修改角色
        int xz = roleDao.update(role);
        //修改中间表
        int dz=middleDao.delMiddle(role.getRoleId());//先删除原始数据
        int gz=middleDao.insertMiddle(role.getRoleId(),menuId);//重新写入
        return xz>0 && dz>0 && gz>0;
    }
}
